package com.hyd.hx_adr.modules.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyd.hx_adr.domain.entity.JsonResult;
import com.hyd.hx_adr.exception.AuthenticationException;
import com.hyd.hx_adr.exception.BusinessException;
import com.hyd.hx_adr.modules.user.domain.entity.User;
import com.hyd.hx_adr.modules.user.domain.info.LoginInfo;
import com.hyd.hx_adr.modules.user.domain.info.RegisterInfo;
import com.hyd.hx_adr.modules.user.domain.vo.LoginVo;
import com.hyd.hx_adr.modules.user.mapper.UserMapper;
import com.hyd.hx_adr.modules.user.service.UserService;
import com.hyd.hx_adr.utils.JWTUtils;
import com.hyd.hx_adr.utils.RedisUtils;
import com.hyd.hx_adr.utils.ResultUtils;
import com.hyd.hx_adr.utils.Sm4Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${config.expireTime}")
    private Long EXPIRE_TIME;

    @Override
    public JsonResult<String> register(RegisterInfo info) {



        return null;
    }

    @Override
    public JsonResult<LoginVo> login(LoginInfo info) {

        if (StringUtils.isBlank(info.getUserName()) || StringUtils.isBlank(info.getPassword()))
            return ResultUtils.error("用户名和密码不能为空");

        String c = redisUtils.get(info.getCodeId() + "_VERIFY_CODE").toString();
        if (!c.equalsIgnoreCase(info.getCode()))
            throw new BusinessException("验证码错误");

        User user = lambdaQuery().eq(User::getUserName, info.getUserName()).one();
        if (null == user)
            return ResultUtils.error("用户不存在");

        String userPwd = Sm4Utils.decode(info.getPassword());
        String localPwd = Sm4Utils.decode(user.getPassword());
        String invalidKey = "PASSWORD_INVALID_" + user.getId();

        Integer count = (Integer) redisUtils.get(invalidKey);
        if (count != null && count >= 5) {
            return ResultUtils.error("用户已被禁用，请十分钟后重试！");
        }

        if (!userPwd.equals(localPwd)) {
            // 记录错误次数
            if (redisUtils.hasKey(invalidKey) && count != null) {
                count++;
                redisUtils.set(invalidKey, count);
            } else {
                redisUtils.set(invalidKey, 1);
            }

            redisUtils.expire(invalidKey, 60 * 10);
            throw new AuthenticationException("用户名或密码错误");
        }

        if (user.getStatus() == 0)
            return ResultUtils.error("用户被禁用，请联系管理员");

        redisUtils.del(info.getCodeId() + "_VERIFY_CODE");

        redisUtils.set(user.getId() + "_ACCESS_TOKEN_", 1);
        redisUtils.set(user.getId() + "_USER_INFO_", JSONObject.toJSONString(user));

        String token = JWTUtils.createJWT(user.getId().toString(), EXPIRE_TIME);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setUserName(user.getUserName());

        return ResultUtils.success(loginVo);
    }
}
